package controller

import (
	"192.168.1.75/go-pkg/errorx"
	"192.168.1.75/go-pkg/helper"
	"192.168.1.75/go-pkg/logx"
	"192.168.1.75/go-pkg/response"
	"github.com/gin-gonic/gin"
	"github.com/samber/lo"
	"sale-admin/internal/app/grpc/client"
	"sale-admin/internal/app/grpc/protoc/system_admin"
	. "sale-admin/internal/app/web/service/goods"
	"sale-admin/internal/models"
	"strconv"
)

type GoodsLogCtrl struct {
	goodsLogService GoodsLogService
}

func (t GoodsLogCtrl) List(c *gin.Context) {
	//type RespDataItem struct {
	//}
	//
	//type RespData struct {
	//	List []RespDataItem `json:"list"`
	//}
	//
	//var reqData RespData
	goodsId := c.Query("goods_id")

	size, _ := strconv.ParseInt(c.DefaultQuery("limit", "10"), 10, 64)
	page, _ := strconv.ParseInt(c.DefaultQuery("page", "1"), 10, 64)

	list, total, err := t.goodsLogService.List(c.Request.Context(), goodsId, helper.NewPageInfo(page, size, []string{}))
	if err != nil {
		logx.Error(c.Request.Context(), "List err: %v", logx.Any("err", err))
		response.JSON(c, nil, errorx.New("查询列表错误", -1))
		return
	}

	cli, err := client.GetSystemAdminClient()
	if err != nil {
		logx.Error(c.Request.Context(), "GetDeviceAdminClient err: %v", logx.Any("err", err))
		response.JSON(c, nil, errorx.New("内部错误", -1))
		return
	}

	merchantIDs := lo.Map(list, func(item *models.MaGoodsInfoLogJoinType, _ int) string {
		return item.MaGoodsInfoLog.MerchantID
	})

	merchantNameRsp, err := cli.MerchantName(c.Request.Context(), &system_admin.MerchantNameReq{
		MerchantIds: merchantIDs,
	})
	if err != nil {
		logx.Error(c.Request.Context(), "MerchantName err: %v", logx.Any("err", err))
		response.JSON(c, nil, errorx.New("内部错误", -1))
		return
	}

	//把根据id，查询expresFeeSetting的名字，把名字映射到OldValue、NewValue
	for i, _ := range list {
		list[i].MaGoodsInfoLog.OldValueMapped = list[i].MaGoodsInfoLog.OldValue
		list[i].MaGoodsInfoLog.NewValueMapped = list[i].MaGoodsInfoLog.NewValue

		if list[i].OldExpressFeeSetting != nil {
			list[i].MaGoodsInfoLog.OldValueMapped = list[i].OldExpressFeeSetting.Name
		}

		if list[i].NewExpressFeeSetting != nil {
			list[i].MaGoodsInfoLog.NewValueMapped = list[i].NewExpressFeeSetting.Name
		}

		list[i].MaGoodsInfoLog.MerchantName = merchantNameRsp.MerchantNameMap[list[i].MaGoodsInfoLog.MerchantID]
	}

	response.JSON(c, gin.H{
		"total": total,
		"page":  page,
		"list":  list,
	}, err)
}
